package mcom.xmks.bluetooth.mesh.base;

//import cn.wch.meshlib.core.MeshServer;

import android.bluetooth.BluetoothDevice;

import cn.wch.meshlib.core.ConCallback;
import cn.wch.meshlib.core.MeshServer;
import mcom.xmks.bluetooth.mesh.dialog.DialogUtil;

public abstract class NodeBaseActivity extends AbstractActivity{
    protected  boolean isConnected;

    /**
     * 连接蓝牙
     * @param mac 蓝牙地址
     */
    protected void connectBLE(String mac){
        MeshServer.getInstance().connect(mac, new ConCallback() {
            @Override
            public void OnError(String mac, Throwable t) {
                showToast(String.format("error:", t.getMessage()));
                isConnected = false;
                runOnUiThread(() -> {
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
            }

            @Override
            public void OnConnecting(String mac) {
                isConnected = false;
                runOnUiThread(()->{
                    DialogUtil.getInstance().showLoadingDialog(NodeBaseActivity.this,"正在连接...");
                });
            }

            @Override
            public void OnConnectSuccess(String mac) {
                showToast("connect success");
                isConnected = true;
                runOnUiThread(()->{
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
                onConnectBLESuccess(mac);
            }

            @Override
            public void OnInvalidDevice(String mac) {
                showToast("not target device");
                runOnUiThread(()->{
                    disconnectBLE(false);
                });
            }

            @Override
            public void OnConnectTimeout(String mac) {
                showToast("connect timeout");
                isConnected = false;
                runOnUiThread(()-> {
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
            }

            @Override
            public void OnDisconnect(String mac, BluetoothDevice bluetoothDevice, int status) {
                isConnected = false;
                runOnUiThread(()-> {
                    DialogUtil.getInstance().hideLoadingDialog();
                    invalidateOptionsMenu();
                });
                showToast("disconnect");
                onBLEDisconnect(mac, status);
            }
        });
    }
    protected void disconnectBLE(boolean force){
        try {
            MeshServer.getInstance().disconnect(force);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    protected boolean isBLEConnected(){
        return MeshServer.getInstance().isConnected();
    }
    protected void onConnectBLESuccess(String mac){};
    protected void onBLEDisconnect(String mac,int status){};
}
